﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.ServiceModel;
using System.Transactions;
using System.Configuration;

[ServiceContract]
public interface IMasterMaintenance
{
    [OperationContract]
    [TransactionFlow(TransactionFlowOption.Allowed)]
    int InsertMasterRecord(string title);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MasterMaintenance : IMasterMaintenance
{
    [OperationBehavior(TransactionAutoComplete = true, TransactionScopeRequired = true)]
    public int InsertMasterRecord(string title)
    {
        int result = 0;
        Console.WriteLine("Master service inserting [{0}]", title);
        using (TransactionScope scope = new TransactionScope())
        {

            Console.WriteLine("\tLocal Txn Id [{0}]\n\tDist Txn Id [{1}]",
                Transaction.Current.TransactionInformation.LocalIdentifier,
                Transaction.Current.TransactionInformation.DistributedIdentifier);

            using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["materConnectionString"]))
            {
                con.Open();
                using (SqlCommand com = new SqlCommand("insert mastertable values (@param); select cast(scope_identity() as int)", con))
                {
                    com.Parameters.AddWithValue("@param", title);
                    result = (int)com.ExecuteScalar();
                }
                con.Close();
            }
            scope.Complete();
        }
        return result;
    }
}


class Program
{
    static void Main(string[] args)
    {
        ServiceHost host = new ServiceHost(typeof(MasterMaintenance));
        host.Open();
        Console.WriteLine("Master Service is listening...");
        Console.ReadLine();
    }
}